﻿#include "biz.h"
#include "ui_biz.h"
#include <QDebug>

Biz::Biz(QWidget *parent) :
    BizEditor(parent),
    ui(new Ui::Biz)
{
    ui->setupUi(this);

    loadDetailColWidthFlag=false;
    table=TD_REJECT_INDEX;
    detailTable=TD_REJECT_DETAIL;

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->indexView->setModel(model);

    detailModel=new QSqlTableModel(this);
    detailModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->detailView->setModel(detailModel);

    ui->indexView->setEditTriggers(QTableView::NoEditTriggers);
    ui->detailView->setEditTriggers(QTableView::NoEditTriggers);

    if(loadColumnWidth())
    {
        loadColumnWidthFlag=true;
        loadDetailColWidthFlag=true;
    }

    updateView();
    createMenu();
}

Biz::~Biz()
{
    delete ui;
}

void Biz::createMenu()
{
    menu=new QMenu(this);
    generateMenu();
}

void Biz::generateMenu()
{
    if(part != "sd")
    {
        menu->addAction(QStringLiteral("添加..."),this,&Biz::newItem);
        menu->addSeparator();
    }
    menu->addAction(QStringLiteral("未完成记录"),this,&Biz::updateView);
    menu->addAction(QStringLiteral("所有记录"),this,&Biz::updateViewAll);
    menu->addSeparator();
    menu->addAction(QStringLiteral("查找..."),this,&Biz::search);

    if(part != "sd")
    {
        menu->addSeparator();
        menu->addAction(QStringLiteral("【报损】"),this,&Biz::en_loss);
        menu->addSeparator();
        menu->addAction(QStringLiteral("进入编辑模式"),this,&Biz::edit_on);
    }
}

void Biz::updateView()
{
    updateViewUnfinish();
}

void Biz::search()
{
    showSearchBox("contact");
}

void Biz::en_remove()
{
    QModelIndex index=ui->detailView->currentIndex();
    if(index.isValid())
    {
        QModelIndex mIndex=index.sibling(index.row(),4);
        if(detailModel->data(mIndex).toString() != ST_WAIT)
        {
            QMessageBox::warning(this,QStringLiteral("状态无效"),QStringLiteral("只有【等待处理】才可以删除！"));
            return;
        }
        detailModel->removeRow(index.row());
    }
}

bool Biz::loadColumnWidth()
{
    if(!QFile::exists(userLand + ETC_BIZ))
        return false;
    else
    {
        QSettings set(userLand + ETC_BIZ,QSettings::IniFormat);
        int width=set.value("Biz/width").toInt();
        int height=set.value("Biz/height").toInt();
        if(width >= 720 && height >= 480)
            this->resize(width,height);

        colWidth.insert(2,set.value("BizColumnWidth/date").toInt());
        colWidth.insert(3,set.value("BizColumnWidth/contact").toInt());
        colWidth.insert(4,set.value("BizColumnWidth/phone").toInt());
        colWidth.insert(5,set.value("BizColumnWidth/express").toInt());
        colWidth.insert(6,set.value("BizColumnWidth/status").toInt());

        detailColWidth.insert(2,set.value("DetailColWidth/name").toInt());
        detailColWidth.insert(3,set.value("DetailColWidth/number").toInt());
        detailColWidth.insert(4,set.value("DetailColWidth/status").toInt());

        return true;
    }
}

void Biz::saveColumnWidth()
{
    QSettings set(userLand + ETC_BIZ,QSettings::IniFormat);
    set.setValue("Biz/width",this->width());
    set.setValue("Biz/height",this->height());

    set.setValue("BizColumnWidth/date",ui->indexView->columnWidth(2));
    set.setValue("BizColumnWidth/contact",ui->indexView->columnWidth(3));
    set.setValue("BizColumnWidth/phone",ui->indexView->columnWidth(4));
    set.setValue("BizColumnWidth/express",ui->indexView->columnWidth(5));
    set.setValue("BizColumnWidth/status",ui->indexView->columnWidth(6));

    set.setValue("DetailColWidth/name",ui->detailView->columnWidth(2));
    set.setValue("DetailColWidth/number",ui->detailView->columnWidth(3));
    set.setValue("DetailColWidth/status",ui->detailView->columnWidth(4));
}

void Biz::setHeaderData()
{
    ui->indexView->hideColumn(0);   //id
    ui->indexView->hideColumn(1);   //uid
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("日期"));    //date
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("联系人"));   //contact
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("手机号"));   //phone
    model->setHeaderData(5,Qt::Horizontal,QStringLiteral("物流方式"));  //express
    model->setHeaderData(6,Qt::Horizontal,QStringLiteral("状态"));    //status
    model->setHeaderData(7,Qt::Horizontal,QStringLiteral("备注"));

    if(loadColumnWidthFlag)
    {
        QMap<int,int>::const_iterator itor;
        for(itor = colWidth.constBegin(); itor != colWidth.constEnd(); itor++ )
        {
            int width=itor.value();
            if(width <= 0)
                width=100;
            else if(width >= this->width())
                width =200;

            ui->indexView->setColumnWidth(itor.key(),width);
        }
    }
}

void Biz::newItem()
{
    BizAdd bizAdd;
    bizAdd.move(this->x() + 50,this->y() + 50);
    bizAdd.exec();
    updateView();
}

void Biz::edit_on()
{
    isEdit=true;
    ui->indexView->setEditTriggers(QTableView::DoubleClicked);
    ui->detailView->setEditTriggers(QTableView::DoubleClicked);
    updateMenu();
}

void Biz::edit_off()
{
    isEdit=false;
    ui->indexView->setEditTriggers(QTableView::NoEditTriggers);
    ui->detailView->setEditTriggers(QTableView::NoEditTriggers);
    updateMenu();
}

void Biz::revert()
{
    if(ui->indexView->currentIndex().isValid())
        model->revertAll();

    if(ui->detailView->currentIndex().isValid())
        detailModel->revertAll();
}

void Biz::save()
{
    if(ui->indexView->currentIndex().isValid())
        model->submitAll();
    if(ui->detailView->currentIndex().isValid())
        detailModel->submitAll();
}

void Biz::updateDetail(const QString &uid)
{
    detailModel->setTable(detailTable);
    detailModel->setFilter(QString("uid = '%1'").arg(uid));
    detailModel->select();

    ui->detailView->hideColumn(0);  //id
    ui->detailView->hideColumn(1);  //uid
    detailModel->setHeaderData(2,Qt::Horizontal,QStringLiteral("名称"));  //name
    detailModel->setHeaderData(3,Qt::Horizontal,QStringLiteral("数量"));  //number
    detailModel->setHeaderData(4,Qt::Horizontal,QStringLiteral("状态"));  //status
    detailModel->setHeaderData(5,Qt::Horizontal,QStringLiteral("检查状况"));

    if(loadDetailColWidthFlag)
    {
        QMap<int,int>::const_iterator itor;
        for(itor = detailColWidth.constBegin(); itor != detailColWidth.constEnd(); itor++ )
        {
            int width=itor.value();
            if(width <= 0)
                width=100;
            else if(width >= this->width())
                width =200;

            ui->detailView->setColumnWidth(itor.key(),width);
        }
    }
}

void Biz::on_indexView_clicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QSqlRecord record=model->record(index.row());
        QString uid=record.value("uid").toString();
        updateDetail(uid);
    }
}

void Biz::en_finish()
{
    QModelIndex index=ui->indexView->currentIndex();
    if(index.isValid())
    {
        QModelIndex mIndex=index.sibling(index.row(),6);
        model->setData(mIndex,ST_FINISH);
    }
}

void Biz::en_loss()
{
    QModelIndex index=ui->detailView->currentIndex();
    if(index.isValid())
    {
        QSqlRecord record=detailModel->record(index.row());
        int detail_id=record.value("id").toInt();

        if(getStatus(detailTable,detail_id) == ST_LOSS)
            return;

        QString uid=record.value("uid").toString();
        QString name=record.value("name").toString();
        QString number=record.value("number").toString();
        QString receiver=QStringLiteral("退货报损");

        QSqlQuery query;
        query.prepare("insert into td_loss (date,name,number,receiver,remark,status) values (?,?,?,?,?,?)");
        query.addBindValue(Env::today);
        query.addBindValue(name);
        query.addBindValue(number);
        query.addBindValue(receiver);
        query.addBindValue(getContactInfo(uid));
        query.addBindValue(ST_WAIT);
        if(query.exec())
        {
            int index_id=getId(table,uid);
            if(getStatus(table,index_id) != ST_RUNNING)
                changeStatus(table,ST_RUNNING,index_id);

            changeStatus(detailTable,ST_LOSS,detail_id);

            updateView();
            updateDetail(uid);
            sendMsg(T_LOSS,LOSS_NOTICE);
        }
    }
}

QString Biz::getContactInfo(const QString &uid)
{
    QString info;
    QSqlQuery query;
    query.exec(QString("select date,contact from %1 where uid='%2'")
               .arg(table)
               .arg(uid));
    if(query.next())
    {
        QString date=query.value(0).toString();
        QString contact=query.value(1).toString();
        info=date + " " + contact + QStringLiteral("退货");
    }
    else
        info="DB ERROR!";
    return info;
}

void Biz::on_indexView_pressed(const QModelIndex &)
{
    ui->detailView->clearSelection();
    ui->detailView->setCurrentIndex(QModelIndex());
}

void Biz::on_detailView_pressed(const QModelIndex &)
{
    ui->indexView->clearSelection();
    ui->indexView->setCurrentIndex(QModelIndex());
}

void Biz::on_indexView_doubleClicked(const QModelIndex &)
{
    if(!isEdit && part != "sd")
        newItem();
}
